import time,os
from Common.connect_to_device import *
from Common.handle_log import do_log
from Common.global_data import GlobalData

import os
import time

def Enter_MainActivity():
    # 删除旧日志文件
    if os.path.exists("device_offline_main.txt"):
        try:
            os.remove("device_offline_main.txt")
        except Exception as e:
            do_log.error(f"删除文件失败: {e}")
    # 确保 device_back 已定义
    if 'device_1' not in globals():
        do_log.error("变量 device_1 未定义，请在调用前设置该变量。")
        raise ValueError("变量 device_1 未定义，请在调用前设置该变量。")

    i = 1
    log_dir = "./Outputs/LogcatLog"

    # 清理日志命令
    cmd_clear = f"adb -s {device_1} logcat -c"
    try:
        os.popen(cmd_clear).readlines()
    except Exception as e:
        do_log.error(f"清理日志时发生错误: {e}")
        return

    while True:
        RunStatus = os.path.exists("main_logcat.txt")
        if not RunStatus:
            now = time.strftime("%Y-%m-%d_%H_%M_%S")
            time.sleep(1)
            try:
                os.popen(cmd_clear).readlines()
                do_log.info(f"{now}清除前排日志成功")
            except Exception as e:
                do_log.error(f"清理日志时发生错误: {e}")

                return

            # 生成日志文件路径
            log_file = os.path.join(log_dir, f"logcat_main_{now}.log")
            cmd_capture = f"adb -s {device_1} logcat -v threadtime -m 1000000 > {log_file}"
            try:
                os.popen(cmd_capture).readlines()
            except Exception as e:
                print(f"捕获日志时发生错误: {e}")
                break
            do_log.info(f"logcat_main_{now}.log")


            i += 1
        else:
            now = time.strftime("%Y-%m-%d_%H_%M_%S")
            do_log.info(now)
            do_log.info("应用出现问题,日志监控终止")
            break



if __name__ == '__main__':
    Enter_MainActivity()